package com.sangeng.runner;

import com.sangeng.domain.entity.Article;
import com.sangeng.mapper.ArticleMapper;
import com.sangeng.utils.RedisCache;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class ViewCountRunner implements CommandLineRunner {
    private final ArticleMapper articleMapper;

    private final RedisCache redisCache;

    @Override
    public void run(String... args) throws Exception {
        //查询数据库中博客信息 id viewCount
        List<Article> articles = articleMapper.selectList(null);

        /*
        破阿里规范，我就不清理，清了我都不知道怎么变成下边的代码
        articles.stream()
                .collect(Collectors.toMap(new Function<Article, Long>() {
                    @Override
                    public Long apply(Article article) {
                        return article.getId();
                    }
                }, new Function<Article, Integer>() {
                    @Override
                    public Integer apply(Article article) {
                        return article.getViewCount().intValue();//ViewCount是Long类型的，但是Long类型的数据存进去redis无法完成递增的操作
                    }
                }));
         */

        Map<String, Integer> viewCountMap = articles.stream()
                .collect(Collectors.toMap(article -> article.getId().toString(), article -> {
                    return article.getViewCount().intValue();//ViewCount是Long类型的，但是Long类型的数据存进去redis无法完成递增的操作
                }));
        //id-viewCount 存储进redis中
        redisCache.setCacheMap("article:viewCount", viewCountMap);
    }
}
